package leetcode.Y2024M6.study;

import leetcode.Y2024M6.TreeNode;
import org.junit.Test;

import java.util.Deque;
import java.util.LinkedList;

public class S226 {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        TreeNode tmp = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(tmp);
        return root;
    }

    public TreeNode invertTreeByStack(TreeNode root) {
        if (root == null) return null;
        Deque<TreeNode> stack = new LinkedList<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node.left != null) stack.add(node.left);
            if (node.right != null) stack.add(node.right);
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }
        return root;
    }

    @Test
    public void test() {
        int[] arr = {4, 2, 7, 1, 3, 6, 9};
        TreeNode tree = TreeNode.createTree(arr);
        TreeNode node = invertTree(tree);
        System.out.println(node);
    }
}
